package com.dat255.tentatime;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.dat255.internalstorage.FavoritesManagement;
import com.dat255.tentatime.es.ExternalStorage;


/**
 * This activity is used for displaying all information 
 * about an exam. It must receive an exam from previous
 * activity
 * @author Joseph
 *
 */
public class ShowExamActivity extends Activity{

	private TextView courseId, courseName, coursePlace, courseTime, courseDate;
	private Exam exam;
	private boolean flag, sucess = false;
	private FavoritesManagement favmanage = new FavoritesManagement(this,15);
	
	
	//variable to login/out
	//private UserState app = ((UserState)ShowExamActivity.this.getApplication());
	
	//TODO: make onOptionsItemSelected better, put comment
	 /** 
     * Called when the activity is first created. 
     * This method will recieve an exam object from the previous activity
     * and display all the details from the exam object
     */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
			super.onCreate(savedInstanceState);
			
			//Set the layout for this activity
			setContentView(R.layout.exam); 
			//Make the GUI components editable
			this.attachGUIcomponents();
			//Get the exam object from previous activity
			this.getExam();
			//Read the exam object and display the information
			this.printExam();
		
	}
	
	/*****************************************************/
	/************** PRIVATE METHODS **********************/
	/*****************************************************/
	
	 /**
     * The internal method will "connect" the input/output components
     * of the GUI for this activity for use in this code
     */
    private void attachGUIcomponents(){
    	
    	 courseId = (TextView) findViewById(R.id.textVCourseID);
		 courseName = (TextView) findViewById(R.id.textVcourseName);
		 coursePlace = (TextView) findViewById(R.id.textVPlace);
		 courseTime = (TextView) findViewById(R.id.textVTime);
		 courseDate = (TextView) findViewById(R.id.textVDate);
    	
    }
    
    /**
     * This method will retrieve the examobject passed from the previous activity
     */
    private void getExam(){
		 Bundle data = getIntent().getExtras();
		 //Get the exam from previos activity
		  exam = data.getParcelable(ShowExamActivity.this.getString(R.string.keySelectedExam));  
		  // The flag is used to determine if the previous activity was an resultactivity or favourite activity
		  flag = data.getBoolean(ShowExamActivity.this.getString(R.string.keyMenuEnable));
    	
    }
    
    /**
     * Display all the details about an exam 
     */
    private void printExam(){
    	
   	 courseId.setText(exam.getCourseID());
	 courseName.setText(exam.getCourseName());
	 coursePlace.setText(exam.getPlace());
	 courseTime.setText(exam.getTime());
	 courseDate.setText(exam.getDate());
    	
    	
    	
    }
	
	/*****************************************************/
	/******************** MENU ***************************/
	/*****************************************************/
	
    
    /**
	 * Creates the menu, with the menu-items specified in the menu xml file
	 */    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

    	getMenuInflater().inflate(R.menu.menu, menu);
	
    	return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

    	
	    	switch(item.getItemId()){
	
		case R.id.itemAddFav:
			String msg;
			if(favmanage.saveFavorite(exam)){
				
				msg = "The exam was added to favourites";
				
			}else{
				
				msg = "Error! The exam was not saved";
			}
			
			Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
			break;
	
		case R.id.itemRemoveFav:
			
		if(favmanage.deleteFavorite(exam)){
			
			Toast.makeText(this, "The exam was succesfully removed", Toast.LENGTH_LONG).show();
			Intent intent = new Intent(); 
            intent.setClass(getApplicationContext(), FavouriteActivity.class);
            startActivity(intent);
            finish();
			
		}else{
			
			Toast.makeText(this, "Error!!", Toast.LENGTH_LONG).show();
			
			
		}
			        	   
			        	   
			        
			break;
			
		case R.id.itemFav:
			startActivity(new Intent(this,FavouriteActivity.class));
			break;
		
		case R.id.itemFind:
			startActivity(new Intent(this, FindActivity.class));
			break;
		case R.id.itemChangeExam:
			Intent examIntent = new Intent(this, ChangeExamActivity.class);
			//Move the selected exam object to next activity
			examIntent.putExtra("changeexam", exam);
			
			startActivity(examIntent);
			
			break;
		case R.id.itemRemoveExam:
			
			AlertDialog.Builder builder1 = new AlertDialog.Builder(ShowExamActivity.this);
			builder1.setMessage("Do you want to delete this exam?")
			       .setCancelable(false)
			       .setTitle("Confirmation")
			       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			
			        	   new RemoveExam().execute();
			
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			
			AlertDialog alert1 = builder1.create();
					alert1.show();
				
			
	    	}

			return true;
			}
    
    
    /**
     * This method will prepare the menu with the desired menu-items
     */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		
		UserState app = ((UserState)ShowExamActivity.this.getApplication());
		super.onPrepareOptionsMenu(menu);
		
		//true: if admin logged in
				if(app.getState()){
					//disable add exam option
					MenuItem itemAddExam = menu.findItem(R.id.itemAddExam);
				    itemAddExam.setVisible(false);
				    itemAddExam.setEnabled(false);
				    //Disable favourite option
					MenuItem itemAddFav = menu.findItem(R.id.itemAddFav);
				    itemAddFav.setVisible(false);
				    itemAddFav.setEnabled(false);
				    //Enable Change
				    MenuItem itemLogout = menu.findItem(R.id.itemChangeExam);
				    itemLogout.setVisible(true);
				    itemLogout.setEnabled(true);
				    //Enable Delete
				    MenuItem itemLogin = menu.findItem(R.id.itemRemoveExam);
				    itemLogin.setVisible(true);
				    itemLogin.setEnabled(true);
					
				}else{
					
					//If the previous activity was an favourite activity
					if(flag){
						//remove favourite option will be available in the menu
						MenuItem item = menu.findItem(R.id.itemRemoveFav);
					    item.setVisible(true);
					    item.setEnabled(true);
						
					}else{
						//if the previous activity was an resultactivity
						//the add favourite option will be available in the menu
						MenuItem item = menu.findItem(R.id.itemAddFav);
					    item.setVisible(true);
					    item.setEnabled(true);
					    
					    
					    //Enable Change
					    MenuItem itemLogout = menu.findItem(R.id.itemChangeExam);
					    itemLogout.setVisible(false);
					    itemLogout.setEnabled(false);
					    //Enable Delete
					    MenuItem itemLogin = menu.findItem(R.id.itemRemoveExam);
					    itemLogin.setVisible(false);
					    itemLogin.setEnabled(false);
				
					
				}
		
			
		}
		
		return true;
		
	}

	/**
	 * This internal class, will help us create an asynctask when we search for exams
	 * based on course name in the server database, instead of burden the UI thread	
	 * @author Joseph
	 *
	 */
	private class RemoveExam extends AsyncTask<Void,Integer,String>{

		/**
		 * This method will search the database after a given coursename
		 * The method will return a list containing the found exams
		 */
		@Override
		protected String doInBackground(Void... userdata) {
			String msg;
			try {

				ExternalStorage.remove(exam.getCourseID());
				msg = "The exam was succesfully deleted!";
				sucess = true;
				
			} catch (java.net.SocketTimeoutException e){
				  
				msg = "The server is busy, Try later!";
				sucess =false;
			}catch (Exception e) {
				msg = "Internal errors!";
				sucess =false;
			}
			
			return msg;
		}
				
		/**
		 * This method is executed after doInBackground and will present the result 
		 * from doInBackground
		 */
		@Override
		protected void onPostExecute(String result) {
			
			
			super.onPostExecute(result);
		
			
			Toast.makeText(ShowExamActivity.this, result, Toast.LENGTH_LONG).show();
			
			//If submit was successful move to next activity
			if(sucess){
				
				
				Intent intent = new Intent(ShowExamActivity.this, FindActivity.class);
				ShowExamActivity.this.startActivity(intent); 
				finish();
						
	    };
	    
			
			
			
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
		
		
	}
	
	

}
